package com.unicloud.medical.oss.client.autoconfigure;

import com.unicloud.medical.oss.client.*;
import com.unicloud.medical.oss.client.properties.OSSClientProperties;
import com.unicloud.medical.oss.client.selector.OssNameSelector;
import com.unicloud.medical.oss.common.constant.ConnectionTypeConstant;
import com.unicloud.medical.oss.common.constant.OSSPropertiesConstant;
import com.unicloud.medical.oss.core.OSSServiceFinder;
import com.unicloud.medical.oss.service.grpc.OSSServiceGrpc;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Nullable;

@ConditionalOnProperty(prefix = OSSPropertiesConstant.OSS_CLIENT_PREFIX, name = "enabled", havingValue = "true")
@Configuration
@AutoConfigureAfter({OssNameSelectorAutoConfiguration.class, OSSGrpcClientAutoConfiguration.class})
@EnableConfigurationProperties({OSSClientProperties.class})
public class OSSClientAutoConfiguration {

    private final OSSClientProperties ossClientProperties;
    private final OssNameSelector defaultOssNameSelector;
    private final OSSServiceFinder ossServiceFinder;

    public OSSClientAutoConfiguration(OSSClientProperties ossClientProperties, OssNameSelector defaultOssNameSelector, OSSServiceFinder ossServiceFinder) {
        this.ossClientProperties = ossClientProperties;
        this.defaultOssNameSelector = defaultOssNameSelector;
        this.ossServiceFinder = ossServiceFinder;
    }

    @Bean
    public OSSClient ossClient(BaseOSSClient baseOSSClient) {
        return new OSSClient(baseOSSClient, defaultOssNameSelector);
    }

    @Bean
    @ConditionalOnProperty(prefix = OSSPropertiesConstant.OSS_CLIENT_PREFIX, name = "connection-type", havingValue = ConnectionTypeConstant.LOCAL)
    public LocalOSSClient localOSSClient() {
        return new LocalOSSClient(ossClientProperties, ossServiceFinder);
    }

    @Bean
    @ConditionalOnProperty(prefix = OSSPropertiesConstant.OSS_CLIENT_PREFIX, name = "connection-type", havingValue = ConnectionTypeConstant.HTTP)
    public HttpOSSClient httpOSSClient() {
        return new HttpOSSClient(ossClientProperties, ossServiceFinder);
    }

    @Bean
    @ConditionalOnProperty(prefix = OSSPropertiesConstant.OSS_CLIENT_PREFIX, name = "connection-type", havingValue = ConnectionTypeConstant.GRPC)
    public GrpcOSSClient grpcOSSClient(@Nullable OSSServiceGrpc.OSSServiceBlockingStub blockStub, @Nullable OSSServiceGrpc.OSSServiceStub stub) {
        return new GrpcOSSClient(ossClientProperties, ossServiceFinder, blockStub, stub);
    }

}
